#!/usr/bin/env node
const fs =require('fs');
async function readEnv(options = {}) {
  let envString = null;
  let envObj = null;
  const inOption = {
    getpath: './.env.develop',
    write: true,
    setPath: './.env.sample',
    source: false,
    ...options,
  };

  function read() {
    return new Promise((resolve) => {
      fs.readFile(inOption.getpath, 'utf-8', (err, data) => {
        if (err) {
          throw new Error(err);
        }
        envString = data;
        resolve(data);
      });
    });
  }
  /**
   * 根据.env.develop 生成 .env.sample
   */
  function generateEnvSample(setPath) {
    let inString = envString;
    // eslint-disable-next-line
    inString = inString.replace(/(?<=\r\n[^\#\s](\w|_)*\=).+(?=\r\n)/g, '');

    if (inOption.source) {
      fs.writeFile(setPath, envString, 'utf-8', (err) => {
        if (err) {
          throw new Error(err);
        }
      });
    } else {
      fs.writeFile(setPath, inString, 'utf-8', (err) => {
        if (err) {
          throw new Error(err);
        }
      });
    }
    
  }

  await read();
  if (inOption.write) generateEnvSample(inOption.setPath);
  return envObj;
}
readEnv({
  getpath: './.env.develop',
  write: true,
  setPath: './.env',
  source: true,
});
